import React from 'react';
import './css/mine.less';
import './css/register.less';
import Address from '../components/Address';
import moment from 'moment';
// import ReactCoreImageUpload  from 'react-core-image-upload';
import ResetPwd from '../components/resetPwd';
import ResetTel from '../components/resetTel';
import Modal from '../components/Modal2';
import Alert from '../components/Alert';
import http from '../../utils/http';
import Cookies from 'js-cookie'
import { VALIDREQUIRED,VALIDENGNAME,VALIDATOR,VALIDNAME } from '../../utils/valid';
import { Toast } from '../components/Toast';
import EventBus from '../../utils/eventBus';

let defaultName = ''
//校验验证对象
const FILEDS = {
    NAME: 'kidChinaName',
    ENGNAME:'kidEngName'
  }
  //与FILEDS映射
  const valids = {
    [FILEDS.NAME]:{
      required: VALIDREQUIRED,
      valid: VALIDNAME
    },
    [FILEDS.ENGNAME]:{
      required: VALIDREQUIRED,
      valid: VALIDENGNAME
    }
  }
  //校验方法
  const required = (field, value) => {
    const valid = valids[field]
    let msg = VALIDATOR(valid, value)
    if (msg) {
      return <div className="text-danger is-visible">{msg}</div>;
    }
  };
let dayInfo ={
    year:'年',
    month:'月',
    day:'日'
}
let staticAllDig ={
    id:'',
    chineseName:'',
    englishName:'',
    gender:1,
    birthday :'2014-01-01',
    cityId:0,
    provinceId:0
}
let user={}
class Mine extends React.Component{
    state={
        yearInfo:false,
        yearList:['年'],
        year:new Date().getFullYear(),
        monthList:['月'],
        dayList:['日'],
        index:111,
        // 模态框的显隐
        telShow:false,
        pswShow:false,
        // 手机号码的传递
        telphone:'',
        allDig :{
            id:'',
            chineseName:'',
            englishName:'',
            gender:1,
            dayInfo :'',
            cityId: 0,
            provinceId:0
        },
        headUrl:'',
        Birthday:{
            year:'年',
            month:'月',
            day:'日'
        },
        setChinaName:'',
        setEnglishName:'',
        alertDig:false
		}
    ShowInfo = () => {
        this.setState({
                pswShow:!this.state.pswShow
        })
        Cookies.remove('token', { path: '/' });
        this.props.history.push('/login/')
	  }
    validChinaName(e){
        let msg = required(FILEDS.NAME,e.target.value);
        this.setState({
            setChinaName:msg
        })
    }
    validEnglishName(e){
        let msg = required(FILEDS.ENGNAME,e.target.value);
        this.setState({
            setEnglishName:msg
        })
    }
    componentWillMount(){
        staticAllDig ={
            chineseName:'',
            englishName:'',
            gender:1,
            birthday :'',
            cityId:0,
            relationId:'',
            provinceId:0
        }
        dayInfo ={
            year:'年',
            month:'月',
            day:'日'
        }
        defaultName=''
    }
    //得到时间，今年往前推12年
    getYear(){
        const date = new Date().getFullYear()-4;
        //年月日时间：
        let dateInfo = date;
        let monthInfo = 1;
        //年月日，数组时间的初始化：
        let yearArr = ['年'];
        let monthArr = ['月'];

        //对于年时间的判断，且放入数组
        while(dateInfo>=date-12){
            yearArr.push(dateInfo);
            dateInfo--; 
        }
        //对于月时间的判断，且放入数组
        while(monthInfo <=12){
            monthArr.push(monthInfo);
            monthInfo++;
        }
        this.setState({
            yearList:yearArr,
            monthList:monthArr
        })
    }
    setData = (data) => {
    user = {
        allDig:{
            englishName:data.englishName,
            chineseName:data.chineseName,
            gender:data.gender,
            id:data.id,
            cityId:data.cityId || 0,
            birthday:data.birthday,
            relationId:data.relationId,
            provinceId:data.provinceId ||0
        },
        headUrl:data.headUrl,
        Birthday:{
            year:moment(Number(data.birthday)).format('YYYYMMDD').substring(0,4),
            month:moment(Number(data.birthday)).format('YYYYMMDD').substring(4,6),
            day:moment(Number(data.birthday)).format('YYYYMMDD').substring(6,8)
        }
      }
      staticAllDig = user.allDig;
      dayInfo = user.Birthday;
      staticAllDig.birthday = user.Birthday.year+'-'+user.Birthday.month+'-'+user.Birthday.day;
      defaultName = data.englishName
      return user
    }
    getKidsDig(){
        http
            .get('/user/find/kidsDetailInfo')
            .then(data => {
                staticAllDig.id = data.id;
                if(data.englishName){
                    const users = this.setData(data || {})       
              // this.setState(
              // {
              //     allDig:{
              //         englishName:data.englishName,
              //         chineseName:data.chineseName,
              //         gender:data.gender,
              //         id:data.id,
              //         cityId:data.cityId,
              //         birthday:data.birthday
              //     },
              //     headUrl:data.headUrl,
              //     Birthday:{
              //         year:moment(Number(data.birthday)).format('YYYYMMDD').substring(0,4),
              //         month:moment(Number(data.birthday)).format('YYYYMMDD').substring(4,6),
              //         day:moment(Number(data.birthday)).format('YYYYMMDD').substring(6,8)
              //     }
              // })
              let days= moment(`${users.Birthday.year}-${users.Birthday.month}`, "YYYY-MM").daysInMonth();
              let dayArr = ['日'];
              for(let i =1;i<=days;i++){
                  dayArr.push(i);
              }
              users.dayList = dayArr
              this.setState(users)
            }
        })
    }
    showAlert(){
        this.setState({
            alertDig:false
        })
    }
    getTelphone(){
        http.get('user/get/accountInfo')
            .then(data=> {
                if(data){
                    this.setState({
                        telphone:data.mobile
                    })
                }
            }, err => {
            })
        }
    KidsInfoStr = (e) => {
        e.preventDefault();
        let isStart = false;
        if(Number(staticAllDig.cityId) === 0){
            staticAllDig.cityId = null;
            staticAllDig.provinceId = null;
        } 
        if(dayInfo.year === "年" || dayInfo.month === "月" || dayInfo.day === "日"){
            isStart = false;
            this.setState({
                alertDig:true
            })
        }else{
            dayInfo.month = dayInfo.month!=='月' && dayInfo.month.slice(1)? dayInfo.month :`0${dayInfo.month}`;
            dayInfo.day = dayInfo.day!=='日' && dayInfo.day.slice(1)? dayInfo.day :`0${dayInfo.day}`
            staticAllDig.birthday = `${dayInfo.year}-${dayInfo.month}-${dayInfo.day}`
            isStart = true;
            for(let i in staticAllDig){
                if(staticAllDig[i]!=='' && staticAllDig.birthday!=="Invalid date"){
                    isStart = true;
                }else{
                    this.setState({
                        alertDig:true
                    })
                    isStart = false;
                }
            }
        }
        if(staticAllDig.cityId&&Number(staticAllDig.provinceId)===0){
            this.setState({
                alertDig:true
            })
            isStart = false;
        } 
            if(isStart){
                http.post('/user/operation/kidsInfo',staticAllDig)
                .then(data=> {
                    if(data){
                      Toast('修改成功!','toast-top')
                      defaultName = true;
                      this.setState();
                      EventBus.$emit('changeImg',{gender:staticAllDig.gender})
                    //   this.props.history.push('/admin');
                    }
                  }, err => {
                })
            }else{
                this.setState({
                    alertDig:true
                })
                return;
            }
        
    }
    componentDidMount(){
      // const data = this.setData({})
      // this.setState(data)
      this.getYear();
      this.getKidsDig();
      this.getTelphone();
    }
    render(){
        return (
            <div className="mine">
                <div className="col-xs-12 col-md-2 mine-left">
                    <ul className="nav-pills mine-nav">
                        <li role="presentation" className={this.state.index===111?'activeInfo':''} onClick={()=>{
                            this.setState({
                                index:111
                            })
                        }} style={{cursor:"pointer"}}><a>小朋友信息</a></li>
                        <li role="presentation" style={{marginLeft:0,cursor:"pointer"}} className={this.state.index===222?'activeInfo':''} onClick={()=>{
                            this.setState({
                                index:222
                            })
                        }}><a>账号密码</a></li>
                        {/* <li role="presentation" className={this.state.index===333?'active':''} onClick={()=>{
                            this.setState({
                                index:333
                            })
                        }}><a>收获地址</a></li> */}
                    </ul>
                </div>
                {
                    this.state.index ===111?
                    <div className="col-xs-12 col-md-9 mine-right">       
                        <div className="col-xs-12">
                            <form>
                             <div className="col-xs-12">
                                <div className="col-md-4 col-xs-12" style={{padding:0}}>
                                    <div className="inp-text" style={{marginTop:"10px"}}>
                                        <label htmlFor="exampleInputText1">中文名</label>
                                    </div>
                                    <div className="inp-border col-xs-12" style={{padding:0}}>
                                        <input  type="text" maxLength= "8" className="intBorder inputText" placeholder='请输入中文名称' autoComplete="off" style={{cursor:"pointer"}} onBlur={(e)=>{this.validChinaName(e)}} value={staticAllDig.chineseName} onChange={(e)=>{
                                            staticAllDig.chineseName=e.target.value;
                                            this.setState({});
                                        }}/>
                                    </div>
                                    <div className="col-xs-12" style={{padding:0}}>
                                    {this.state.setChinaName}  
                                    </div>                                  
                                 </div>
                                 <div className="col-md-6 col-xs-12" style={{padding:0}}>
                                    <div className="inp-text" style={{marginTop:"10px"}}>
                                        <label htmlFor="exampleInputPassword1">英文名</label>
                                    </div>
                                    <div className="inp-border col-xs-12" style={{padding:0,color:defaultName?'#A5B9BF':""}}>
                                        <input type="text" maxLength="20" className="intBorder inputText" style={{color:defaultName?'#A5B9BF':"",cursor:"pointer"}} placeholder='请输入英文名称' autoComplete="off" onBlur={(e)=>{if(!defaultName){this.validEnglishName(e)}}} readOnly={defaultName ? 'readOnly':''} value={staticAllDig.englishName} onChange={(e)=>{
                                            staticAllDig.englishName=e.target.value;
                                            this.setState({});
                                        }}/>
                                    </div>
                                    {
                                    !defaultName?
                                    <div className="col-xs-12 inp-text" style={{margin:"10px 0",padding:0}}>
                                        只可编辑一次
                                    </div>:""
                                    }
                                    <div className="col-xs-12" style={{padding:0}}>
                                        {this.state.setEnglishName}
                                    </div>
                                    
                                 </div>
                             </div>
                             <div className="col-xs-12">
                                <div className="inp-text" style={{marginTop:user.allDig&&user.allDig.englishName?'56px':'36px'}}>
                                    <label htmlFor="exampleInputPassword1">您与小朋友的关系</label>
                                </div>
                                <div className="border-sel">
                                  <select className="intBorder" autoComplete="off" value={staticAllDig.relationId} style={{cursor:"pointer"}} onChange={(e)=>{
                                            staticAllDig.relationId = e.target.value;
                                            this.setState({})   
                                      }}>
                                      {!staticAllDig.relationId?<option value='' style={{display:"none"}}></option>:''}
                                      <option value="1">父亲</option>
                                      <option value="2">母亲</option>
                                      <option value="3">其他</option>
                                    </select>
                                 </div>
                             </div>
                             <div className="col-xs-12">
                                <div className="inp-text">
                                    <label htmlFor="exampleInputPassword1">性别</label>
                                </div>
                                 <label className="radio-inline" style={{marginRight:"30px",padding:0}} onClick={(e)=>{if(!isNaN(e.target.value)){(staticAllDig.gender=e.target.value)}}}>
                                     <input type="radio" name="inlineRadioOptions" className="radioClass" id="inlineRadio1" value="1" autoComplete="off" checked ={Number(staticAllDig.gender)===1?'checked':''} onChange={(e)=>{
                                         staticAllDig.gender=e.target.value;
                                         this.setState({})
                                     }} style={{cursor:"pointer",width:"50px",height:"20px"}}/> 
                                     {
                                        Number(staticAllDig.gender) === 1?<img src={require('../../images/icon/full-all-t.png')} style={{width:"16px",height:"16px"}} alt=""/>:
                                        <img src={require('../../images/icon/full-two.png')} style={{width:"16px",height:"16px"}} alt=""/>
                                    }
                                     <span className="inputText" style={{fontSize:"18px",lineHeight:'28px'}}>男孩</span>
                                 </label>
                                 <label className="radio-inline" onClick={(e)=>{if(!isNaN(e.target.value)){(staticAllDig.gender=e.target.value)}}}>
                                     <input type="radio" name="inlineRadioOptions" className="radioClass" id="inlineRadio2" value="2" autoComplete="off" checked ={Number(staticAllDig.gender)===2?'checked':''} onChange={(e)=>{
                                        staticAllDig.gender=e.target.value;
                                        this.setState({})
                                     }} style={{cursor:"pointer",width:"50px",height:"20px"}}/>
                                     {
                                        Number(staticAllDig.gender) === 2?<img src={require('../../images/icon/full-all-t.png')} style={{width:"16px",height:"16px"}} alt=""/>:
                                        <img src={require('../../images/icon/full-two.png')} style={{width:"16px",height:"16px"}} alt=""/>
                                    }
                                     <span className="inputText" style={{fontSize:"18px",lineHeight:'28px'}}>女孩</span>
                                 </label>
                             </div>
                             <div className="btn-group  col-xs-12">
                                <div className="inp-text">
                                    <label htmlFor="exampleInputPassword1">出生日期</label>
                                </div>
                                <div className="col-xs-12" style={{padding:0}}>
                             {/* 年，月，日三个下拉框模块 */}
                                    <div className="border-sel">
                                        <select className="intBorder" value={dayInfo.year} autoComplete="off" style={{cursor:"pointer"}} onChange={(e)=>{
                                            dayInfo.year = e.target.value;
                                            this.setState({})                                  
                                        }}>
                                            {
                                                this.state.yearList.map((item,i)=>{
                                                    return <option key={`y${i}`} value={item}>{item}</option>
                                                })
                                            }
                                        </select>

                                 </div>
                                 {/* 月，通过年和月来判断每月的天数 */}
                                 <div className="border-sel">
                                    <select className="intBorder" autoComplete="off" style={{cursor:"pointer"}} value={Number(dayInfo.month.substring(0,1))===0?dayInfo.month.substring(1,2):dayInfo.month} onChange={(e)=>{
                                            dayInfo.month = e.target.value;
                                            if(dayInfo.month &&  dayInfo.year && dayInfo.month!=="月" && dayInfo.year!=="年"){
                                                dayInfo.month = dayInfo.month!=='月' && dayInfo.month.slice(1)? dayInfo.month :`0${dayInfo.month}`;
                                                let days= moment(`${dayInfo.year}-${dayInfo.month}`, "YYYY-MM").daysInMonth();
                                                let dayArr = ['日'];
                                                for(let i =1;i<=days;i++){
                                                    dayArr.push(i);
                                                }
                                                this.setState({
                                                    dayList:dayArr
                                                })
                                            }
                                            this.setState({})   
                                        }}>
                                        {
                                            this.state.monthList.map((item,i)=>{
                                                return <option key={`m${i}`} value={item}>{item}</option>
                                            })
                                        }
                                    </select>
                                </div>
                                <div className="border-sel">
                                    <select className="intBorder" style={{cursor:"pointer"}} autoComplete="off" value={Number(dayInfo.day.substring(0,1))===0?dayInfo.day.substring(1,2):dayInfo.day} onChange={(e)=>{
                                            dayInfo.day = e.target.value;
                                            this.setState({})   
                                        }}>
                                        {
                                            this.state.dayList.map((item,i)=>{
                                                return <option key={`d${i}`} value={item}>{item}</option>
                                            })
                                        }
                                    </select>
                                 </div>
                                 </div>
                                 <div className="col-xs-12" style={{padding:0}}>
                                    <div className="col-xs-12 col-md-10" style={{padding:0}}>
                                        <Address getCity={(cityIdig)=>{
                                            staticAllDig.cityId = cityIdig.cityid;
                                            staticAllDig.provinceId = cityIdig.cityVosid;
                                            this.setState({})
                                        }} cityid ={staticAllDig.cityId} provinceid={staticAllDig.provinceId}></Address>
                                    </div>
                                    <div className="col-xs-12 col-md-2" style={{paddingLeft:"40px"}}>
                                        <input type="button" className="btn btn-save" style={{margin:"86px 0 40px 0",outline:'none'}} onClick={event=>{this.KidsInfoStr(event)}} value="保存"/>
                                    </div>
                                </div>
                             </div>
                         </form>
                    </div>
                    <div className="position-img">
                         <div>
                             {Number(staticAllDig.gender) ===1?<img className="img-circle" src={this.state.headUrl||require('../../images/main/boy.png')} alt=''/>:<img className="img-circle" src={this.state.headUrl||require('../../images/main/girl.png')} alt=''/>}
                         </div>
                         <span style={{display:'inline-block',width:"90px",textAlign:'center',cursor:"pointer"}} ></span>
                         {/* <button type="submit" className="btn btn-default">修改头像</button> */}
                         {/* <ReactCoreImageUpload
                             text="修改头像"
                             className="btn btn-default"
                             inputOfFile="files"
                             url="http://101.198.151.190/api/upload.php"
                             imageUploaded={this.imageuploaded}>
                         </ReactCoreImageUpload> */}
                    </div>
                 </div>:''
                }
                {
                    this.state.index ===222?<div className="col-md-9 mine-right">
                    <div className="col-xs-12">
                        <div className="col-md-9 col-xs-12 tel-title">
                            <label htmlFor="exampleInputEmail1">当前登录手机号</label>
                            <p className="p-text" style={{textAlign:'left'}}>{this.state.telphone}</p>
                        </div>
                        <div className="button-group col-xs-12 col-md-3" style={{margin: "20px 0 60px 0"}}>
                            <button type="submit" className="btn btn-float" onClick={()=>{
                                this.setState({
                                    telShow:!this.state.telShow
                                })
                            }}>修改号码</button>
                        </div>
                    </div>
                    <div className=" col-xs-12">
                        <div className="col-xs-12 col-md-9 tel-title">
                            <label htmlFor="exampleInputPassword1">登录密码</label>
                        </div>
                        <div className="button-group col-xs-12 col-md-3">
                            {/* ‘修改密码’点击时，模态框显示出来 */}
                            <button type="submit" className="btn btn-float"  style={{margin: "20px 0 60px 0"}} onClick={()=>{
                                this.setState({
                                    pswShow:!this.state.pswShow
                                })
                            }}>修改密码</button>
                        </div>
                    </div>
                    {
                        // 修改手机号：：模态框的显隐进行判断
                        this.state.telShow?<Modal>
                                                <div className='modal-content-l'>
                                                <button type="button" className="close-X"  onClick={()=>{
                                                        this.setState({
                                                            telShow:!this.state.telShow
                                                        })
                                                    }}><img src={require('../../images/XX.png')} alt=""/></button>
                                                    <div className="content-center">
                                                        <ResetTel ShowInfo={()=>{
                                                                this.setState({
                                                                    telShow:!this.state.telShow
                                                                })
                                                                Cookies.remove('token', { path: '/' });
                                                                this.props.history.push('/login/')
                                                            }} telphone={this.state.telphone}></ResetTel>
                                                    </div>
                                                </div>
                                           </Modal>:''
                    }
                 </div>:''
                }
                {/* {
                    this.state.index ===333?<div className="col-md-9 mine-right">
                    33
                 </div>:''
                } */}
                {this.state.alertDig?
                <Alert text={'请输入完整信息'} showAlert = {()=>this.showAlert()}></Alert>:""    
            }
            <div className={this.state.pswShow?'show':'hide'}>
              <Modal>
                <div>
                    <button type="button" className="close-X paswordclose" style={{marginRight:"15px"}} onClick={()=>{
                        this.setState({
                            pswShow:!this.state.pswShow
                        })
                    }}><img src={require('../../images/XX.png')} alt=""/></button>
                    <div className="row register">
                      <div className="find-content" style={{minWidth:"554px"}}>
                        <div className="reset-title">修改密码</div>
                        <ResetPwd ShowInfo={this.ShowInfo} telphone={this.state.telphone} type="1"></ResetPwd>
                      </div>
                    </div>
                    {/* <div className="content-center">
                        <ResetPwd ShowInfo={} telphone={this.state.telphone}></ResetPwd>
                    </div> */}
                </div>
              </Modal>
            </div>
            </div>
        )
    }
}
export default Mine;